package com.qian.api.ddj.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class MD5Utils {

	public static String getSign(Map<String, String> params, String key) {
		StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
		MD5Utils.buildPrePayParams(buf, params, false);
		String preStr = buf.toString();
        System.out.println("signDate:"+preStr);
		return DigestUtils.md5Hex(getContentBytes(preStr + "&KEY=" + key, "utf-8"));
	}
	
	public static String getSign(JSONObject params, String key) {
		if(params.containsKey("SIGN_DAT")){
			String sign = params.getString("SIGN_DAT");
			System.out.println("接收签名="+sign);
			params.remove("SIGN_DAT");
		}
		StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
		MD5Utils.buildPayParams(buf,params,false);
		String preStr = buf.toString();
        System.out.println("signDate:"+preStr);
		return DigestUtils.md5Hex(getContentBytes(preStr + "&KEY=" + key, "utf-8"));
	}
	
	public static boolean checkSign(JSONObject params,String key){
		boolean result = false;
		if(params.containsKey("SIGN_DAT")){
			String sign = params.getString("SIGN_DAT");
			System.out.println("接收签名="+sign);
			params.remove("SIGN_DAT");
			StringBuilder buf = new StringBuilder((params.size() +1) * 10);
			MD5Utils.buildPayParams(buf,params,false);
			String preStr = buf.toString();
			String signRecieve = DigestUtils.md5Hex(getContentBytes(preStr + "&KEY=" + key, "utf-8"));
			System.out.println("签名结果=" + signRecieve);
			result = sign.equalsIgnoreCase(signRecieve);
		}
		return result;
	}
	
	public static void main(String args[]){
	
	}

	public static void buildPrePayParams(StringBuilder sb,Map<String, String> payParams,boolean encoding){
		List<String> keys = new ArrayList<String>(payParams.keySet());
		Collections.sort(keys);
		for(String key : keys){
            String str = payParams.get(key);
            if (str == null || str.length() == 0)
            {
                //空串不参与sign计算
                continue;
            }
			sb.append(key).append("=");
			if(encoding){
				sb.append(urlEncode(str));
			}else{
				sb.append(str);
			}
			sb.append("&");
		}
		System.out.println(sb.toString());
		sb.setLength(sb.length() - 1);
	}
	
	public static void buildPayParams(StringBuilder sb,JSONObject payParams,boolean encoding){
		List<String> keys = new ArrayList<String>(payParams.keySet());
		Collections.sort(keys);
		for(String key : keys){
            String str = payParams.getString(key);
            if (str == null || str.length() == 0)
            {
                //空串不参与sign计算
                continue;
            }
			sb.append(key).append("=");
			if(encoding){
                sb.append(urlEncode(str));
			}else{
				sb.append(str);
			}
			sb.append("&");
		}
		System.out.println(sb.toString());
		sb.setLength(sb.length() - 1);
	}

	public static String urlEncode(String str) {
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (Throwable e) {
			return str;
		}
	}

	private static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {

			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:"
					+ charset);
		}
	}

}
